package com.onemile.app;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.onemile.app.base.BaseUINoBottom;
import com.onemile.controls.AdpLV_Address;
import com.onemile.data.DXml;
import com.onemile.data.DXml.Field;
import com.onemile.data.DXml.FieldList;
import com.onemile.entity.MessageCode;
import com.onemile.entity.PubConst;
import com.onemile.entity.Session;
import com.onemile.entity.model.EAddress;
import com.onemile.entity.model.EOrder;
import com.onemile.net.NetClient;
import com.onemile.utils.UtiDialogsFactory;

/**
 * 跳转需要传入的参数BooleanExtra(PubConst.Key.INTENT_IS_ADDRESS_MANAGER, true/false);
 * 
 * @author lichen
 * 
 */
public class UISettlementAddress extends BaseUINoBottom
{
   private boolean IsAddressManager;

   private ListView listAddress;

   // private AdpLV_Address adp;

   private void InitControls()
   {
	  listAddress = (ListView) findViewById(R.id.list_ordersettle_address);
   }

   private void InitControlsEvent()
   {
	  listAddress.setOnItemClickListener(new AdapterView.OnItemClickListener()
	  {
		 @Override
		 public void onItemClick(AdapterView<?> parentView, View currentView, final int position, long arg3)
		 {
			if (!IsAddressManager)
			{
			   try
			   {
				  Intent intent = new Intent();
				  Session.getInstance().setAddressCache((EAddress) listAddress.getAdapter().getItem(position));
				  setResult(Activity.RESULT_OK, intent);
				  finish();
			   }
			   catch (Exception e)
			   {
				  if (Session.getInstance().IsDEBUG())
				  {
					 Log.e("ERROR", "UISettlementAddress.InitControlsEvent().new OnItemClickListener() {...}.onItemClick(...).new ITaskCallBack() {...}_DoWhenComplete(result) ", e);
				  }
			   }
			}
		 }
	  });
	  listAddress.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
	  {
		 @Override
		 public boolean onItemLongClick(AdapterView<?> parentView, View currentView, final int position, long arg3)
		 {
			UtiDialogsFactory.getInstance().ShowItemsDialog(UISettlementAddress.this,
				  new String[] { getString(R.string.all_setdefault), getString(R.string.all_edit), getString(R.string.all_delete) }, new DialogInterface.OnClickListener()
				  {
					 @Override
					 public void onClick(DialogInterface dialog, int which)
					 {
						try
						{
						   switch (which)
						   {
							  case 0:// 设为默认
								((AdpLV_Address)listAddress.getAdapter()).SetDefault(position);
								 break;
							  case 1:// 编辑
								 Intent intent = new Intent();
								 intent.setClass(UISettlementAddress.this, UISettlementAddressNewEdit.class);
								 Session.getInstance().setAddressCache((EAddress) listAddress.getAdapter().getItem(position));
								 startActivityForResult(intent, PubConst.ActivityCode.SETTLE_ADDRESS);
								 break;
							  case 2:// 删除
								 UtiDialogsFactory.getInstance().ShowOKCancelAlertDialog(UISettlementAddress.this, getString(R.string.dialog_tips), getString(R.string.dialog_are_you_sure_delete),
									   new DialogInterface.OnClickListener()
									   {
										  @Override
										  public void onClick(DialogInterface dialog, int which)
										  {
                                            dialog.dismiss();
											executeAsyncTask(PubConst.TaskName.SETTLE_ADDRESS_DELETE, new Object[] { ((EAddress) listAddress.getAdapter().getItem(position)).getUserAddressId(),position });
										  }
									   });
								 break;
						   }
						}
						catch (Exception e)
						{
						   if (Session.getInstance().IsDEBUG())
						   {
							  Log.e("ERROR", "UISettlementAddress.InitControlsEvent().new OnItemLongClickListener() {...}.onItemLongClick(...).new OnClickListener() {...}_onClick(dialog, which) ", e);
						   }
						}
					 }
				  });
			return false;
		 }
	  });
   }

   @Override
   protected void onCreateOverride(Bundle savedInstanceState)
   {
	  InitControls();
	  InitControlsEvent();
	  executeAsyncTask(PubConst.TaskName.SETTLE_ADDRESS_LIST);
   }

   @Override
   public int SetContentViewLayoutResId()
   {
	  return R.layout.settlement_address;
   }

   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data)
   {
	  if (requestCode == PubConst.ActivityCode.SETTLE_ADDRESS)
	  {
		 if (resultCode == Activity.RESULT_OK)
		 {
			executeAsyncTask(PubConst.TaskName.SETTLE_ADDRESS_LIST);
		 }
	  }
   }

   @Override
   public boolean onKeyDown(int keyCode, KeyEvent event)
   {
	  if (keyCode == event.KEYCODE_BACK)
	  {
		 finish();
	  }
	  return false;
   }

   @Override
   public void SetTopToolbar(TextView topTxt, ImageView leftImBtn, ImageView rightImgBtn, RelativeLayout rightRay, TextView cartNum)
   {
	  try
	  {
		 topTxt.setVisibility(View.VISIBLE);
		 IsAddressManager = getIntent().getBooleanExtra(PubConst.Intent_Key.IS_ADDRESS_MANAGER, false);
		 if (IsAddressManager)
		 {
			topTxt.setText(getString(R.string.title_addressmanager));
		 }
		 else
		 {
			topTxt.setText(getString(R.string.title_addressselect));
		 }
		 rightRay.setVisibility(View.VISIBLE);
		 cartNum.setVisibility(View.GONE);
		 rightImgBtn.setImageResource(R.drawable.settle_add);
		 rightImgBtn.setOnClickListener(new View.OnClickListener()
		 {
			@Override
			public void onClick(View v)
			{
			   Intent intent = new Intent();
			   intent.setClass(UISettlementAddress.this, UISettlementAddressNewEdit.class);
			   intent.putExtra(PubConst.Intent_Key.IS_NEW_ADDRESS, true);
			   startActivityForResult(intent, PubConst.ActivityCode.SETTLE_ADDRESS);
			}
		 });
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "UISettlementAddress_SetTopToolbar(topImg, topTxt, leftImBtn, rightImgBtn) ", e);
		 }
	  }
   }

   @Override
   public void onAsyncTaskStart(String taskName, Object[] params)
   {
	  if (taskName.equals(PubConst.TaskName.SETTLE_ADDRESS_LIST))// 获取列表
	  {
		 UtiDialogsFactory.getInstance().ShowLoadingDialogNoTitle(UISettlementAddress.this, getString(R.string.dialog_loading));
	  }
	  if (taskName.equals(PubConst.TaskName.SETTLE_ADDRESS_DELETE))// 删除
	  {
		 UtiDialogsFactory.getInstance().ShowLoadingDialogNoTitle(UISettlementAddress.this, getString(R.string.dialog_please_wait));
	  }
   }

   @Override
   public Object onAsyncTaskInBackground(String taskName, Object[] params) throws Exception
   {
	  try
	  {
		 if (taskName != null && taskName.equals(PubConst.TaskName.SETTLE_ADDRESS_LIST))
		 {
			return NetClient.GetAddressListByUserId(Session.getInstance().getUserInfo().getUserId());
		 }
		 if (taskName != null && taskName.equals(PubConst.TaskName.SETTLE_ADDRESS_DELETE))
		 {
			return NetClient.DelAddress(String.valueOf(params[0]));
		 }
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "UISettlementAddress_onAsyncTaskInBackground(taskName, params) ", e);
		 }
	  }
	  return null;
   }

   @Override
   public void onAsyncTaskEnd(String taskId, String taskName, final Object[] params, Object result)
   {
	  try
	  {
		 UtiDialogsFactory.getInstance().DismissLoadingDialog();
		 if (result != null)
		 {
			DXml data = (DXml) result;

			if (taskName.equals(PubConst.TaskName.SETTLE_ADDRESS_LIST))
			{
			   int size = data.getBody().getFieldLists().length;
			   ArrayList<EAddress> list = new ArrayList<EAddress>();
			   EAddress address = null;
			   for (int i = 0; i < size; i++)
			   {
				  FieldList fl = data.getBody().GetFieldList(i);
				  address = new EAddress();
				  address.setAddressName(fl.GetFieldValue("AddressName"));
				  address.setConsignee(fl.GetFieldValue("Consignee"));
				  address.setAddress(fl.GetFieldValue("Address"));
				  address.setMobile(fl.GetFieldValue("Mobile"));
				  address.setUserAddressId(fl.GetFieldValue("UserAddressId"));
				  list.add(address);
			   }

			   AdpLV_Address adp = new AdpLV_Address(UISettlementAddress.this, list);
			   listAddress.setAdapter(adp);
			}
			if (taskName.equals(PubConst.TaskName.SETTLE_ADDRESS_DELETE))
			{
			   if (data.getHead().GetFieldValue("RspCode").equals(MessageCode.Success.Code))
			   {
                  UtiDialogsFactory.getInstance().ShowOKAlertDialog(UISettlementAddress.this, getString(R.string.dialog_tips), getString(R.string.dialog_del_success),new DialogInterface.OnClickListener()
				  {
				     @Override
				     public void onClick(DialogInterface dialog, int which)//弹出成功对话框
				     {
				  	   ((AdpLV_Address)listAddress.getAdapter()).RemoveAddress(Integer.valueOf(String.valueOf(params[1])));
				  	   dialog.dismiss();
				     }
				  });
			   }
			   else
			   {
				  UtiDialogsFactory.getInstance().ShowToastInfoShort(UISettlementAddress.this, data.getHead().GetFieldValue("RspMsg"));
			   }
			}
		 }
		 else
		 {
			UtiDialogsFactory.getInstance().ShowToastInfoShort(UISettlementAddress.this, getString(R.string.dialog_server_failed));
		 }
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "UISettlementAddress_onAsyncTaskEnd(taskId, taskName, params, result) ", e);
		 }
	  }
   }

}